package com.example.nft.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

/**
 * @program: stcn-parent
 * @description: post get util
 * @author: hong.jiahao
 * @create: 2021-08-15 18:02
 */
public class HttpUtil {
    // json数据请求
    public static String sendPost(String requestUrl,String json){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(requestUrl);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");//表示客户端发送给服务器端的数据格式
        //httpPost.setHeader("Accept", "*/*");这样也ok,只不过服务端返回的数据不一定为json
        httpPost.setHeader("Accept", "application/json");                    //表示服务端接口要返回给客户端的数据格式，
        StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        try{
            CloseableHttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
            System.out.println(statusCode);//200
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity respEnt = response.getEntity();
                String respHtml = EntityUtils.toString(respEnt, "UTF-8");
                JSONObject jsonObject = JSONObject.parseObject(respHtml);//响应结果
                return jsonObject.toJSONString();
            }
        }catch (Exception e){

        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("res","");
        return jsonObject.toJSONString();

    }

    // 带form表单数据发送请求
    public static JSONArray sendRequestWithFormdata(String url, Map<String, String> mapdata,String token) {
		System.out.println(url);
        CloseableHttpResponse response = null;
        //cookie
        BasicCookieStore store = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(store).build();

        // 创建httppost
        HttpPost httpPost = new HttpPost(url);
        try {
            // 设置提交方式
            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.addHeader("Finger-Nft-Token", token);
            // 添加参数
            List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
            if (mapdata.size() != 0) {
                // 将mapdata中的key存在set集合中，通过迭代器取出所有的key，再获取每一个键对应的值
                Set keySet = mapdata.keySet();
                Iterator it = keySet.iterator();
                while (it.hasNext()) {
                    String k = (String) it.next();// key
                    String v = mapdata.get(k);// value
                    nameValuePairs.add(new BasicNameValuePair(k, v));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 获得http响应体
            HttpEntity entity = response.getEntity();
            Map<String,Object> map = new HashMap<>();
            // 读取cookie信息
            List<Cookie> cookielist = store.getCookies();
            List<String> cookievalue = new LinkedList<>();
            for (Cookie cookie : cookielist) {
                cookievalue.add(cookie.getValue().toString());
                map.put("cookie",cookievalue);
            }
            if (entity != null) {
                // 响应的结果
                String content = EntityUtils.toString(entity, "UTF-8");
                JSONObject json = JSON.parseObject(content);
                JSONArray data = json.getJSONArray("data");
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static Map sendRequesRefer(String url, Map<String, String> mapdata) {
        System.out.println(url);
        System.out.println(mapdata.toString());
        CloseableHttpResponse response = null;
        //cookie
        BasicCookieStore store = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(store).build();

        // 创建httppost
        HttpPost httpPost = new HttpPost(url);
        try {
            // 设置提交方式
            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec("www.gxylnews.com.cn").build();
            // 添加参数
            List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
            if (mapdata.size() != 0) {
                // 将mapdata中的key存在set集合中，通过迭代器取出所有的key，再获取每一个键对应的值
                Set keySet = mapdata.keySet();
                Iterator it = keySet.iterator();
                while (it.hasNext()) {
                    String k = (String) it.next();// key
                    String v = mapdata.get(k);// value
                    nameValuePairs.add(new BasicNameValuePair(k, v));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpPost.setConfig(requestConfig);
            System.out.println("nameValuePairs:" + nameValuePairs);
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 获得http响应体
            HttpEntity entity = response.getEntity();
            Map<String,Object> map = new HashMap<>();
            // 读取cookie信息
            List<Cookie> cookielist = store.getCookies();
            List<String> cookievalue = new LinkedList<>();
            for (Cookie cookie : cookielist) {
                cookievalue.add(cookie.getValue().toString());
                map.put("cookie",cookievalue);
            }
            if (entity != null) {
                // 响应的结果
                String content = EntityUtils.toString(entity, "UTF-8");
                map.put("content",content);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
